package me.seu.demo.config;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elasticsearch Configuration
 *
 * @author liangfeihu
 * @since 2023/6/30 14:39
 */
@Configuration
public class ElasticsearchConfig {

    private String host = "106.14.88.135";
    private Integer port = 9200;

    @Bean
    public ElasticsearchClient coElasticsearchClient() {
        ElasticsearchTransport transport = getElasticsearchTransport();

        // And create the API client
        return new ElasticsearchClient(transport);
    }

    private ElasticsearchTransport getElasticsearchTransport() {
        // Create the low-level client
        RestClient restClient = RestClient.builder(new HttpHost(host, port))
                        .setDefaultHeaders(compatibilityHeaders())
                .build();

        // Create the transport with a Jackson mapper
        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }

    private Header[] compatibilityHeaders() {
        return new Header[]{
                new BasicHeader("X-Elastic-Product", "Elasticsearch"),
                new BasicHeader(HttpHeaders.ACCEPT, "application/json;charset=UTF-8"),
                new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8")};
    }

    private ElasticsearchTransport getElasticsearchTransportWithAuth() {
        // Create the credentials provider
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "password"));

        // Create the low-level client
        RestClient restClient = RestClient.builder(new HttpHost(host, port))
                .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
                .build();

        // Create the transport with a Jackson mapper
        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }
}